<?php
/**
 * Mongodb类
 */
class framework_base_mongodb {
	public $mConn = NULL, $error = '';
	public static $_instance = array();

	private $DbName = '';

	private function __construct($username = '', $password = '', $dbname = '', $type = 0, $autoClose = 0, $server = '') {
		$options = array(
				'connect' => true,
			);

		if (empty($dbname))
			$dbname = MONGODB_DB;
		if (empty($username))
			$username = MONGODB_USER;
		if (empty($password))
			$password = MONGODB_PWD;

		if (defined('MONGODB_REPLICASET') && MONGODB_REPLICASET) {
			$options['replicaSet'] = MONGODB_REPLICASET;
			$serverDNS = 'mongodb://' . $username . ':' . $password . '@' . MONGODB_HOST . '/' . $dbname;	// 如果是replica set模式，则MONGODB_HOST应该是一个带端口并且逗号分隔的host串
		}else {
			$serverDNS = 'mongodb://' . $username . ':' . $password . '@' . MONGODB_HOST . ":" . MONGODB_PORT . '/' . $dbname;
		}

		if (defined('MONGODB_TIMEOUT') && MONGODB_TIMEOUT) {
			$options['connectTimeoutMS'] = MONGODB_TIMEOUT;
		}

		try {
			//framework_static_function::write_log(json_encode($serverDNS), 'mongo');  // 没必要每次连接都写日志
			$this -> mConn = new MongoClient($serverDNS, $options);
		} catch (Exception $exc) {
			$error_msg = json_encode(array(
				"code" => '10002',
				"msg" => $exc -> getMessage()
			));
			framework_static_function::write_log($error_msg, 'mongo');
			//exit ;
		}
		if ($autoClose) {
			// register_shutdown_function(array(&$this, 'close_pdooci'));
		}
	}

	/**
	 * 返回的连接状态
	 * @author	jonah.fu
	 * @date	2012-04-21
	 * @param	int			type			是否长联接
	 * @param	int			autoClose		是否自动关闭连接
	 * @param	int			autoClose		是否自动关闭
	 * @param	array		ociDbServer		数据库信息，参考 config.php 文件
	 * @param	string		ociConnectStr	数据库连接字符串，参考 config.php 文件
	 *
	 * @return	framework_base_mongodb		返回pdo_oci_obj 对象
	 */
	public static function connect($username = '', $password = '', $dbName = '', $type = 0, $autoClose = 0, $server = '') {
		$arrStr = md5($server);
		if (empty(self::$_instance) || !(self::$_instance[$arrStr] instanceof self)) {

			// 如果是长联接则不自动关闭
			if ($type)
				$autoClose = 0;
			self::$_instance[$arrStr] = new self($username, $password, $dbName, $type, $autoClose, $server);
		}
		return self::$_instance[$arrStr];
	}

	/**
	 * 选择DB
	 */
	public function select_db($dbName) {
		if (empty($dbName)){
            throw new Exception("database name is null");
        }
		$this -> DbName = $dbName;
	}

	/**
	 * 插入记录
	 *
	 * 参数：
	 * $table_name:表名
	 * $record:记录
	 *
	 * 返回值：
	 * 成功：true
	 * 失败：false
	 */
	public function insert($table_name, $record) {
		$dbname = $this -> DbName;
		try {
			$this -> mConn -> $dbname -> $table_name -> insert($record, array('safe' => true));
			return true;
		} catch (MongoCursorException $e) {
			$this -> error = $e -> getMessage();
			return false;
		}
	}

	/**
	 * 查询表的记录数
	 *
	 * 参数：
	 * $table_name:表名
	 *
	 * 返回值：表的记录数
	 */
	function count($table_name) {
		$dbname = $this -> DbName;
		return $this -> mConn -> $dbname -> $table_name -> count();
	}

}
?>  